package com.ceyear.my_idcard;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;


public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_STORAGE_PERMISSION = 100;
    private static final int REQUEST_GALLERY = 101;
    private static final int REQUEST_GALLERY_FRONT = 102;
    private static final int REQUEST_GALLERY_BACK = 103;
    private int currentRequestCode;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Button frontButton = findViewById(R.id.idcardfrontrecongnition);
        frontButton.setOnClickListener(v -> requestStoragePermissionAndOpenGallery(REQUEST_GALLERY_FRONT));
        Button backButton = findViewById(R.id.idcardbackrecongnition);
        backButton.setOnClickListener(v -> requestStoragePermissionAndOpenGallery(REQUEST_GALLERY_BACK));
    }

    private void requestStoragePermissionAndOpenGallery(int requestCode) {
        //检查是否已经授予读取外部存储权限（Manifest.permission.READ_EXTERNAL_STORAGE）。如果未授予权限，则请求该权限。
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
        } else {
            //如果权限已经被授予，调用 openGallery 方法打开系统相册
            openGallery(requestCode);
        }
    }

    private void openGallery(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, requestCode);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openGallery(currentRequestCode);
            } else {
                Toast.makeText(this, "Storage permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
                String base64Str = bitmapToBase64(bitmap);
                if (requestCode == REQUEST_GALLERY_FRONT) {
                    new NetworkTask_idcardfrontrecongnition().execute(base64Str);
                } else if (requestCode == REQUEST_GALLERY_BACK) {
                    new NetworkTask_idcardbackrecongnition().execute(base64Str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String bitmapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

    private class NetworkTask_idcardfrontrecongnition extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String base64Str = params[0];
            String host = "https://zidv2.market.alicloudapi.com";
            String path = "/thirdnode/ImageAI/idcardfrontrecongnition";
            String appcode = "dfa840e41e35455c9adf0552c5590e99";
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + appcode);
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<>();
            Map<String, String> bodys = new HashMap<>();
            bodys.put("base64Str", base64Str);

            try {
                return HttpUtils.doPost(host, path, headers, querys, bodys);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                try {
                    JSONObject jsonResponse = new JSONObject(result);
                    int errorCode = jsonResponse.getInt("error_code");
                    if (errorCode == 0) {
                        JSONObject jsonResult = jsonResponse.getJSONObject("result");
                        String idCardNo = jsonResult.getString("idcardno");
                        String name = jsonResult.getString("name");

                        Toast.makeText(MainActivity.this, "Name: " + name + "\nID Card No: " + idCardNo, Toast.LENGTH_LONG).show();

                        // 调用 verifyID 函数
                        AliyunAPIHelper.verifyID(idCardNo, name, new AliyunAPIHelper.AliyunAPIResponseListener() {
                            @Override
                            public void onSuccess(String response) {
                             Log.d("MainActivity",response);
                                runOnUiThread(() -> Toast.makeText(MainActivity.this, "Verification successful: " + response, Toast.LENGTH_LONG).show());
                                try {
                                    JSONObject verificationResponse = new JSONObject(response);
                                    JSONObject verificationResult = verificationResponse.getJSONObject("result");
                                    boolean isok = verificationResult.getBoolean("isok");

                                    if (isok) {
                                        Toast.makeText(MainActivity.this, "ID verification successful", Toast.LENGTH_LONG).show();
                                    } else {
                                        Toast.makeText(MainActivity.this, "ID verification failed", Toast.LENGTH_LONG).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(MainActivity.this, "JSON Parsing error", Toast.LENGTH_LONG).show();
                                }
                            }

                            @Override
                            public void onFailure(Exception e) {
                                runOnUiThread(() -> Toast.makeText(MainActivity.this, "Verification failed", Toast.LENGTH_LONG).show());
                            }
                        });

                    } else {
                        String reason = jsonResponse.getString("reason");
                        Toast.makeText(MainActivity.this, "Error: " + reason, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "JSON Parsing error", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(MainActivity.this, "Request failed", Toast.LENGTH_LONG).show();
            }
        }


    }

    private class NetworkTask_idcardbackrecongnition extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String base64Str = params[0];
            String host = "https://zidv2.market.alicloudapi.com";
            String path = "/thirdnode/ImageAI/idcardbackrecongnition";
            String appcode = "dfa840e41e35455c9adf0552c5590e99";
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + appcode);
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<>();
            Map<String, String> bodys = new HashMap<>();
            bodys.put("base64Str", base64Str);

            try {
                return HttpUtils.doPost(host, path, headers, querys, bodys);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                Toast.makeText(MainActivity.this, "Response: " + result, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "Request failed", Toast.LENGTH_LONG).show();
            }
        }
    }
}